<?php

/**
 *
 * @author Administrator
 */
class UserController {
	// TODO - Insert your code here
	private $lan;

	/**
	 */
	function __construct() {

		if (isset( $_REQUEST[PARAM_LAN])) {
			$this->lan = $_REQUEST[PARAM_LAN];
		} else {
			$this->lan = DEFAULT_LANGAUGE;
		}
	}

	/**
	 * check login function
	 */
	public function checkLogin() {

		if (isset( $_SESSION[SESSION_USERNAME]) && ! empty( $_SESSION[SESSION_USERNAME])) {
			return array(STATUS => STATUS_OK, USER_USERNAME => $_SESSION[SESSION_USERNAME]);
		} else {
			return array(STATUS => STATUS_FAIL, USER_USERNAME => null);
		}
	}
	
	/**
	 * logot function
	 */
	public function userLogout() {
		
		unset($_SESSION[SESSION_USERNAME]);
		return array(STATUS => STATUS_OK, USER_USERNAME => null);
	}

	/**
	 * login function
	 */
	public function userLogin() {

		$username = $_REQUEST[USER_USERNAME];
		$password = $_REQUEST[USER_PASSWORD];
		
		$db = new DBAccess();
		$checkUsername = $db->selectCountRecord( USERS, array(USER_USERNAME => $username));
		
		if ($checkUsername > 0) {
			
			$checkPassword = $db->selectCountRecord( USERS, array(USER_USERNAME => $username, SQL_AND, USER_PASSWORD => $password));
			
			if ($checkPassword > 0) {
				$_SESSION[SESSION_USERNAME] = $username;
				return array(STATUS => STATUS_OK, USER_USERNAME => $_SESSION[SESSION_USERNAME]);
			} else {
				return array(STATUS => STATUS_FAIL, USER_USERNAME => null , USER_PASSWORD => STATUS_ERROR);
			}
			
		} else {
			return array(STATUS => STATUS_FAIL, USER_USERNAME => STATUS_ERROR , USER_PASSWORD => null);
		}
	
	}

	/**
	 * regist new user
	 */
	public function userRegist() {
		
		$username = $_REQUEST[USER_USERNAME];
		$password = $_REQUEST[USER_PASSWORD];
		
		$db = new DBAccess();
		$checkUsername = $db->selectCountRecord( USERS, array(USER_USERNAME => $username));
		
		if ($checkUsername > 0){
			return array(STATUS => STATUS_FAIL, USER_USERNAME => STATUS_ERROR , USER_PASSWORD => null);
		} else {
			
			$user = array(USER_ID => 0, USER_USERNAME => $username, USER_PASSWORD => $password, USER_EMAIL => $username, USER_ROLE => USER_TYPE_ENDUSER, USER_TYPE => USER_TYPE_ENDUSER);
			if ($db->insertData($user, USERS)){
				if (!isset($_SESSION[SESSION_USERNAME])){
					$_SESSION[SESSION_USERNAME] = $username;
					return array(STATUS => STATUS_OK, USER_USERNAME => $username);
				}
				return array(STATUS => STATUS_OK, USER_USERNAME => null);
			} else {
				return array(STATUS => STATUS_FAIL, USER_USERNAME => null , USER_PASSWORD => null);
			}
		}
	}

	public function newRegist() {

	}

	/**
	 */
	function __destruct() {
		
		// TODO - Insert your code here
	}
}

?>